package tcpchat02;

import udp.MyClient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建服务器
 * 写出数据:输出流
 * 读取数据:输入流
 */
public class Server {
    private List<MyChannel> all=new ArrayList<MyChannel>();
    public static void main(String[] args) {
        new Server().start();
    }

    public void start(){
        try {
            ServerSocket server=new ServerSocket(8888);
            Socket socket=server.accept();
            MyChannel myChannel=new MyChannel(socket);
            all.add(myChannel);//加入到容器中统一管理
            new Thread(myChannel).start();//一条道路
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 一个客户端一条道路
     */
    private class MyChannel implements Runnable{
        private DataInputStream dis;
        private DataOutputStream dos;
        private boolean isRunning=true;
        public MyChannel(Socket socket){
            try {
                dis=new DataInputStream(socket.getInputStream());
                dos=new DataOutputStream(socket.getOutputStream());
            } catch (IOException e) {
                //e.printStackTrace();
                isRunning=false;
                CloseUtil.closeAll(dis,dos);
            }
        }

        /**
         * 读取数据
         * @return
         */
        private String receive(){
            String msg="";
            try {
                msg=dis.readUTF();
            } catch (IOException e) {
                //e.printStackTrace();
                isRunning=false;
                CloseUtil.closeAll(dis);
                all.remove(this);//移除自身
            }
            return msg;
        }

        /**
         * 发送数据
         */
        private void send(String msg){
            if (msg!=null&&!msg.equals("")){
                try {
                    dos.writeUTF(msg);
                    dos.flush();
                } catch (IOException e) {
                    //e.printStackTrace();
                    isRunning=false;
                    CloseUtil.closeAll(dos);
                    all.remove(this);//移除自身
                }
            }else {
                return;
            }
        }
        private void sendOthers(){
            String msg=this.receive();
            //遍历容器
            for (MyChannel other:all) {
                if (other==this){
                    continue;
                }
                //发送给其他客户端
                else {
                    other.send(msg);
                }
            }
        }
        @Override
        public void run() {
            while(isRunning){
                //send(receive());//自己发给自己
                sendOthers();
            }
        }
    }
}
